package controller;

import entity.ResultInfo;
import entity.User;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;
import service.impl.UserServiceImpl;
import util.Base64Utils;
import util.Constants;
import util.MD5Utils;
import util.UuidUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * 用户模块的controller
 *
 * @version 1.0
 * @Author: xxf
 * @CreateDate: 2020/9/25 22:24
 */
@WebServlet("/user")
public class UserController extends BaseController {

    private UserService service = new UserServiceImpl();

    /**
     * 验证用户名是否注册
     *
     * @param request
     * @param response
     */
    public void checkUser(HttpServletRequest request, HttpServletResponse response) {
        //获取参数
        String username = request.getParameter("username");
        //设置响应消息对象
        ResultInfo info = new ResultInfo();
        if (username == null) {
            //不能注册
            info.setFlag(false);
            info.setErrorMsg("名字不能为空");
        }
        boolean flag = false;
        //调用service查找是否存在用户
        flag = service.checkUserName(username);
        if (flag) {
            //此用户名不存在，可以注册
            info.setFlag(true);
        } else {
            //用户名已存在，不能注册
            info.setFlag(false);
            info.setErrorMsg("用户名已存在");
        }
        //给客户端响应
        try {
            writeValue(info, response);
        } catch (IOException e) {
            System.out.println("用户名注册响应异常");
            e.printStackTrace();
        }

    }

    /**
     * 用户注册
     *
     * @param request
     * @param response
     * @return
     */
    public String register(HttpServletRequest request, HttpServletResponse response) {
        //获取验证码
        String check = request.getParameter("checkCode");
        HttpSession session = request.getSession();
        String checkcode = (String) session.getAttribute(Constants.CHECKCODE);
        session.removeAttribute(Constants.CHECKCODE);
        //校验验证码
        if (checkcode == null || check == null || !checkcode.equalsIgnoreCase(check)) {
            request.getSession().setAttribute("registerMsg", "验证码有误");

        }

        //获取用户信息
        Map<String, String[]> map = request.getParameterMap();

        User getUser = new User();
        try {
            BeanUtils.populate(getUser, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        //已经赋值了：用户名，密码，邮箱，性别
        //没赋值：状态，激活码，用户类型
        //完善用户信息
        getUser.setUstatus(Constants.USER_NOT_ACTIVE);//未激活状态
        getUser.setUrole(Constants.ROLE_CUSTOMER);//普通用户
        getUser.setUcode(UuidUtil.getUuid());//UUID工具类生成随机数字

        //密码加密处理
        getUser.setUpassword(MD5Utils.md5(getUser.getUpassword()));


        //调用service进行注册
        int row = service.registerUser(getUser);
        if (row > 0) {
            //注册成功
            return Constants.REDIRECT + "/registerSuccess.jsp";
        }
        //设置响应消息
        request.setAttribute("registerMsg", "注册失败");
        //响应
        return Constants.REDIRECT + "/register.jsp";
    }

    /**
     * 激活-->通过发送邮箱url路径，用户访问后调用active方法改变用户激活状态
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取激活码
        String code = request.getParameter("code");
        if (code != null) {
            boolean flag = service.active(code);
            String msg = null;
            if (flag) {
                //激活成功
                msg = "激活成功，请<a href='http://localhost:8080/MiShop/login.jsp'>登录</a>";
            } else {
                msg = "激活失败，请联系管理员";

            }
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(msg);
        }
    }

    /**
     * 登录
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //验证码校验
        String vcode = request.getParameter("vcode");
        HttpSession session = request.getSession();
        String checkCode = (String) session.getAttribute(Constants.CHECKCODE);
        //校验验证码
        if (checkCode == null || !checkCode.equalsIgnoreCase(vcode)) {
            session.setAttribute("msg", "验证码有误");

        }

        //获取参数
//        Map<String, String[]> map = request.getParameterMap();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String auto = request.getParameter("auto");

        //调用service层查询用户表
        User user = service.login(username, password);

        //设置响应信息
        //如果getUser为空，表示数据库中查询不到
        if (user == null) {
            request.setAttribute("msg", "账号或者密码错误");
            return Constants.FORWARD + "/login.jsp";
        }
        //如果不为空但没有激活
        if (Constants.USER_NOT_ACTIVE.equals(user.getUstatus())) {
            request.setAttribute("msg", "用户未激活，请先激活");
            return Constants.FORWARD + "/login.jsp";
        }
        //登录成功
        session.setAttribute("loginUser", user);

        //自动登录两周
        if (auto != null) {
            //将用户名密码进行base64处理
            String encode = Base64Utils.encode(username + ":" + password);
            //保存cookie
            Cookie cookie = new Cookie(Constants.AUTO_NAME, encode);
            cookie.setPath("/");
            cookie.setMaxAge(14 * 24 * 60 * 60);
            response.addCookie(cookie);

        } else {
            //清空cookie
            Cookie cookie = new Cookie(Constants.AUTO_NAME, "");
            //清空路径
            cookie.setPath("/");
            //设置存活时间
            cookie.setMaxAge(0);
            //添加响应
            response.addCookie(cookie);
        }

        //响应
        return Constants.REDIRECT + "/index.jsp";
    }


    /**
     * 注销登录，返回主页
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //登录时存储的session数据，key为loginUser
        request.getSession().removeAttribute("loginUser");
        //清空cookie
        Cookie cookie = new Cookie(Constants.AUTO_NAME, "");
        //清空路径
        cookie.setPath("/");
        //设置存活时间
        cookie.setMaxAge(0);
        //覆盖在客户端的cookie信息
        response.addCookie(cookie);
        request.setAttribute("msg", "注销成功");

        return Constants.REDIRECT + "/index.jsp";
    }

}
